package com.hzhr.iot.device.aop;

import com.hzhr.iot.core.constant.Common_ErrorsEnum;
import com.hzhr.iot.core.constant.HzhrAttrNames;
import com.hzhr.iot.core.exception.ServiceException;
import com.hzhr.iot.log.sdk.model.log.LogModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
@Order(1)
public class ServiceAspect {
    @Autowired
    HttpServletRequest request;


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.hzhr.iot.device.service..*(..))")
    public void httpPointCut() {
    }

    @Before("httpPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
    }

    @AfterReturning(returning = "ret", pointcut = "httpPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
    }

    @Around("httpPointCut()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws ServiceException {
        try {
                Object result = joinPoint.proceed();
            return result;
        } catch (ServiceException e) {
            LogModel log = (LogModel)request.getAttribute(HzhrAttrNames.LOG);
            log.appendExceptionInfo(e);

            throw e;
        }  catch (Throwable e) {
            logger.error("未知异常", e);
            LogModel log = (LogModel)request.getAttribute(HzhrAttrNames.LOG);
            log.appendExceptionInfo(e);

            throw new ServiceException(Common_ErrorsEnum.COMMON_0);
        }
    }
}